import { EventEmitter } from 'events'
/**
 * 解决TCP粘包问题
 * 主流解决办法：数据以定长 header(2个字节) + body(若干字节)的格式来封装
 * 过程：
 * 维护一个数组pipe,每次接收到data就push到pipe中
 * 然后判断pipe的长度是否够2个字节，够就读出header的值
 * 从而得到body的长度， 这个package的长度就是header + body
 * 从而的出这次传输的具体数据
 */

export class Pipe extends EventEmitter {
	private pipe: Buffer = Buffer.alloc(0)

	constructor() {
		super()
	}

	push(buffer: Buffer) {
		this.pipe = Buffer.concat([this.pipe, buffer])
		while (this.pipe.length > 2) {
			const bodyLength = this.pipe.readUInt16BE(0)
			const packLength = bodyLength + 2
			if (this.pipe.length >= packLength) {
				const data = this.pipe.subarray(2, packLength)
				this.pipe = this.pipe.subarray(packLength)
				this.emit('data', data)
			} else {
				break
			}
		}
	}

	pack(data: any) {
		const body = Buffer.from(JSON.stringify(data))
		const header = Buffer.alloc(2)
		header.writeUInt16BE(body.length)
		const buffer = Buffer.concat([header, body])
		return buffer
	}
}
